import {Component, OnInit} from '@angular/core';
import {AccountStatService} from "./account-stat.service";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {PageSubject} from "../../../util/page-subject";
import {ResponseUtil} from "../../../util/response-util";
import {MsgResult} from "../../../models/msg-result";
import {MsgConstants} from "../../../constants/constants";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";

declare var echarts;
declare var $;
declare var moment;

@Component({
  selector: 'app-account-stat',
  templateUrl: './account-stat.component.html',
  styleUrls: ['./account-stat.component.css']
})
export class AccountStatComponent implements OnInit {

  visitDateType: string = 'month';
  accountDateType: string = 'month';
  intervalDateType: string = 'month';
  dateConfig: any;

  constructor(private accountStatService: AccountStatService,
              private dialogService: OneDialogService,
              private pageSubject: PageSubject,
              private responseUtil: ResponseUtil) {
  }

  ngOnInit() {
    this.initStatisticalAnalysis();
    this.pushPage();

  }


  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("基础管理", "");
    this.pageSubject.pushPage("账户访问统计", "统计模块");
  }

  initStatisticalAnalysis(){
    this.getDailyVisits();
    this.getTerminalVisitType();

    this.initDatePlugins('visitDate');
    this.initDatePlugins('accountDate');
    this.initDatePlugins('intervalDate');
  }

  /**
   * 初始化时间插件
   * @param id : 页面选择器id
   */
  initDatePlugins = (id) => {
    let elem = $('#'+id);
    this.dateConfig = {
      format: 'yyyy-mm',
      autoclose: true,
      minView: 3,
      startView: 3,
      language: 'zh-CN',
      initialDate:new Date()
    };
    elem.val(moment().format('YYYY-MM'.toUpperCase()));
    let dateObj = elem.datetimepicker(this.dateConfig).on('changeDate', (e)=>{
      this.searchDateData(e)
    });
    this[id+'Obj'] = dateObj;

    let params = 'timeType='+'month';
    // 初始化访问量，新增账户，访问次数量模块
    this.getVisitNumber(params);
    this.getStatisticsVisits(params);
    this.getNewAccount(params);
  };

  /**
   *
   * @param e
   */
  searchDateData = (e) => {
    let date = e.target.value;
    let chartType = $(e.target).attr('id');
    let timeType = this[chartType+'Type'];
    if (timeType.indexOf('Now') !== -1) {
      timeType = timeType.replace('Now', '');
    }
    this[chartType+'Type'] = timeType;
    let dateArr = this.startAndEndDate(date,chartType);
    let params = 'startTime='+dateArr[0]+'&endTime='+dateArr[1]+'&timeType='+timeType;
    if('visitDate' == chartType){
      this.getStatisticsVisits(params);
    }
    if('accountDate' == chartType){
      this.getNewAccount(params);
    }
    if('intervalDate' == chartType){
      this.getVisitNumber(params);
    }

  };

  /**
   *
   * @param date
   * @param chartType
   * @returns {[any , any]}
   */
  startAndEndDate(date,chartType){
    let monthDay,visitStartDate,visitEndDate;
    if (this[chartType+'Type'] == 'year') {
      visitStartDate = date+'-01-01 00:00:00';
      visitEndDate = date+'-12-31 23:59:59';
      if (moment().year() === moment(date).year()) {
        monthDay = this.dayOfMonth(moment(date).year(),moment().month()+1);
        visitEndDate = moment().format('YYYY-MM')+'-'+monthDay+' 23:59:59';
      }
    } else {
      monthDay = this.dayOfMonth(moment(date).year(),moment(date).month()+1);
      visitStartDate = date+'-01 00:00:00';
      visitEndDate = date+'-'+monthDay+' 23:59:59';
      if (moment().year() === moment(date).year() &&　moment().month() === moment(date).month()) {
        visitEndDate = moment().format('YYYY-MM-DD HH:mm:ss');
      }
    }
    return [visitStartDate,visitEndDate]
  }

  dayOfMonth = (year,month) => {
    let d = new Date(year,month,0);
    return d.getDate()
  };


  /**
   *  用于年/月切换时，初始化年月格式并初始化数据。
   * @param dateType : 时间类型标签：month/year
   * @param chartType : 统计类型标签：访问统计：visit,新增账户：account，访问次数：interval
   */
  selectDateType( dateType: string, chartType: string ,isNowDate?:boolean){
    this[chartType+'DateType'] = dateType;
    if(isNowDate){
      this[chartType+'DateType'] = dateType+'Now';
    }
    let visitDateObj = this[chartType+'DateObj'];
    let date = visitDateObj.val();
    visitDateObj.datetimepicker('remove');
    let view = dateType == 'month' ? 3 : 4;
    let formatter = dateType == 'month' ? 'yyyy-mm' : 'yyyy';
    let dateConfig = {
      format: formatter,
      autoclose: true,
      minView: view,
      startView: view,
      language: 'zh-CN',
      initialDate:new Date()
    };
    if(moment().year() === moment(date).year()){
      date = moment().format(formatter.toUpperCase())
    }else{
      date = moment(date).format(formatter.toUpperCase())
    }
    visitDateObj.val(date);
    visitDateObj.datetimepicker(dateConfig);

    if('visit'== chartType){
      let params = 'timeType='+dateType;
      // if(!isNowDate){
      //   let dateArr = this.startAndEndDate(date,chartType+'Date');
      //   params += '&startTime='+dateArr[0]+'&endTime='+dateArr[1];
      // }

      if(isNowDate){
        this.getStatisticsVisits(params);
      }


    }

    if('account'== chartType){
      let params = 'timeType='+dateType;
      // if(!isNowDate){
      //   let dateArr = this.startAndEndDate(date,chartType+'Date');
      //   params += '&startTime='+dateArr[0]+'&endTime='+dateArr[1];
      // }

      if(isNowDate){
        this.getNewAccount(params);
      }

    }

    if('interval'== chartType){
      let params = 'timeType='+dateType;
      // if(!isNowDate){
      //   let dateArr = this.startAndEndDate(date,chartType+'Date');
      //   params += '&startTime='+dateArr[0]+'&endTime='+dateArr[1];
      // }
      if(isNowDate){
        this.getVisitNumber(params);
      }

    }

  }

  /**
   * 获取日访问总量
   */
  getDailyVisits() {

    this.accountStatService.getStatisticsDailyVisitsByTime().subscribe(
      result => this.responseUtil.success(result, this.processDailyVisitsResulr),
      error => this.responseUtil.error(error)
    );
  }

  processDailyVisitsResulr = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   * 获取访问量
   * @param params: 条件参数
   */
  getStatisticsVisits(params) {
    this.accountStatService.getStatisticsVisitsByTime(params).subscribe(
      resuult => this.responseUtil.success(resuult, this.processStatisticsVisitsResult),
      error => this.responseUtil.error(error)
    );
  }

  processStatisticsVisitsResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.statisticsVisitsEcharts(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   *  时间段访问量折线柱状图
   * @param data ：数据
   */
  statisticsVisitsEcharts(data) {
    // 基于准备好的dom，初始化echarts图表
    let myChart = echarts.init(document.getElementById('visitChart'));
    let option = {
      title: {
        text: data.textTopic,
        subtext: '实时统计'
      },
      tooltip: {
        trigger: 'axis',
        formatter:function(params){
          params[0].value = params[0].value?params[0].value:"-";
          return params[0].name+" </br>"+params[0].seriesName+":"+params[0].value;
        }
      },
      legend: {
        data: data.legendList,
        selectedMode: false
      },
      toolbox: {
        show: true,
        feature: {
          mark: {show: true},
          dataView: {show: true, readOnly: false},
          magicType: {show: true, type: ['line', 'bar']},
          restore: {show: true},
          saveAsImage: {show: true}
        }
      },
      calculable: true,
      xAxis: [
        {
          type: 'category',
          data:data.timeList
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: data.visitType,
          type: 'bar',
          data: data.visitsList,
          barMaxWidth:40,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          },
          itemStyle:{
            normal:{
              color:'#368EFD'
            }
          }
        },
        {
          name: data.visitType,
          type: 'line',
          data: data.visitsList,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          },
          itemStyle:{
            normal:{
              color:'#89C935'
            }
          }
        }
      ]
    };
    // 为echarts对象加载数据
    myChart.setOption(option);
  }


  /**
   *  获取新增账户量
   */
  getNewAccount(params) {
    this.accountStatService.getNewAccountByTime(params).subscribe(
      resuult => this.responseUtil.success(resuult, this.processNewAccountResult),
      error => this.responseUtil.error(error)
    );
  }

  processNewAccountResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.NewAccountEcharts(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   * 时间段新增账户折线柱状图
   * @param data
   */
  NewAccountEcharts(data) {
    // 基于准备好的dom，初始化echarts图表
    let myChart = echarts.init(document.getElementById('new_account'));

    let option = {
      title: {
        text: data.textTopic,
        subtext: '实时统计'
      },
      tooltip: {
        trigger: 'axis',
        formatter:function(params){
          params[0].value = params[0].value?params[0].value:"-";
          return params[0].name+" </br>"+params[0].seriesName+":"+params[0].value;
        }
      },
      legend: {
        selectedMode: false,
        data: data.legendList
      },
      toolbox: {
        show: true,
        feature: {
          mark: {show: true},
          dataView: {show: true, readOnly: false},
          magicType: {show: true, type: ['line', 'bar']},
          restore: {show: true},
          saveAsImage: {show: true}
        }
      },
      calculable: true,
      xAxis: [
        {
          type: 'category',
          data:data.timeList
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: data.visitType,
          type: 'bar',
          data: data.newAccountList,
          barMaxWidth:40,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          },
          itemStyle:{
            normal:{
              color:'#368EFD'
            }
          }
        } ,
        {
          name: data.visitType,
          type: 'line',
          data: data.dayNewAccountList,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          },
          itemStyle:{
            normal:{
              color:'#89C935'
            }
          }
        }
      ]
    };
    // 为echarts对象加载数据
    myChart.setOption(option);
  }

  /**
   *  统计区段访问次数总量
   */
  getVisitNumber(params) {
    // let params = 'startTime='+'2017-11-01 00:00:00'+'&endTime='+'2017-11-08 14:30:38'+'&timeType='+'month';
    this.accountStatService.getVisitNumber(params).subscribe(
      resuult => this.responseUtil.success(resuult, this.processVisitNumberResult),
      error => this.responseUtil.error(error)
    );
  }

  processVisitNumberResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.visitNumberEcharts(result.data[0]);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   * 区间访问次数访问量折线柱状图
   * @param data
   */
  visitNumberEcharts(data) {
    // 基于准备好的dom，初始化echarts图表
    let myChart = echarts.init(document.getElementById('interval_visit_number'));

    let option = {
      title: {
        text: '某一区段内访问总量',
        subtext: '实时统计'
      },
      tooltip: {
        trigger: 'axis',
        formatter:function(params){
          params[0].value = params[0].value?params[0].value:"-";
          return params[0].name+" </br>"+params[0].seriesName+":"+params[0].value;
        }
      },
      legend: {
        selectedMode: false,
        data: ['区段访问次数']
      },
      color:['#368EFD','#89C935'],
      toolbox: {
        show: true,
        feature: {
          mark: {show: true},
          dataView: {show: true, readOnly: false},
          magicType: {show: true, type: ['line', 'bar']},
          restore: {show: true},
          saveAsImage: {show: true}
        }
      },
      calculable: true,
      xAxis: [
        {
          type: 'category',
          data:data.spacingList
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '访问量',
          type: 'bar',
          barMaxWidth:40,
          data: data.visitNum,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          },
          itemStyle:{
            normal:{
              color:'#368EFD'
            }
          }
        }, {
          name: '访问量',
          type: 'line',
          data: data.visitNum,
          itemStyle:{
            normal:{
              color:'#89C935'
            }
          }
        }
      ]
    };
    // 为echarts对象加载数据
    myChart.setOption(option);
  }

  /**
   *  获取用户访问终端的类型数据
   */
  getTerminalVisitType() {
    this.accountStatService.getTerminalVisitType().subscribe(
      resuult => this.responseUtil.success(resuult, this.processTerminalVisitResult),
      error => this.responseUtil.error(error)
    );
  }

  processTerminalVisitResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.terminalVisitTypeEcharts(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   *
   * @param data
   */
  terminalVisitTypeEcharts(data){
    // 基于准备好的dom，初始化echarts图表
    let myChart = echarts.init(document.getElementById('terminal_visit_type'));
    let option = {
      title : {
        text: '终端访问类型',
        subtext: '实时数据',
        x:'center'
      },
      tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        selectedMode: false,
        orient : 'vertical',
        x : 'left',
        data:['PC','APP']
      },
      color:['#368EFD','#89C935'],
      toolbox: {
        show : true,
        feature : {
          mark : {show: true},
          dataView : {show: true, readOnly: false},
          magicType : {
            show: true,
            type: ['pie', 'funnel'],
            option: {
              funnel: {
                x: '25%',
                width: '50%',
                funnelAlign: 'left',
                max: 1548
              }
            }
          },
          restore : {show: true},
          saveAsImage : {show: true}
        }
      },
      calculable : true,
      series : [
        {
          name:'访问来源',
          type:'pie',
          radius : '55%',
          center: ['50%', '60%'],
          data:data
        }
      ]
    };

    myChart.setOption(option);
  }

}

